import { app, BrowserWindow, screen } from 'electron'
import * as path from 'path'
import { log } from './logger'
import { codeListener } from './code-listener'
import { dialogListener } from './dialog-listener'
import { rootPath, serve } from './env'

log.info('electron starting', rootPath)

let win: BrowserWindow | null = null

function createWindow(): BrowserWindow {
    const size = screen.getPrimaryDisplay().workAreaSize
    win = new BrowserWindow({
        autoHideMenuBar: true,
        x: 0,
        y: 0,
        // width: size.width,
        // height: size.height,
        width: 620,
        height: 860,
        webPreferences: {
            nodeIntegration: true,
            allowRunningInsecureContent: serve
        }
    })

    if (serve) {
        require('devtron').install()
        win.webContents.openDevTools()

        require('electron-reload')(__dirname, {
            electron: require(path.resolve(__dirname, '../node_modules/electron'))
        })
        win.loadURL('http://localhost:4200')
    } else {
        win.loadURL(`file://${__dirname}/ui/index.html`)
    }

    win.on('closed', () => {
        win = null
    })
    codeListener(win)
    dialogListener(win)

    // const exePath = path.dirname(app.getPath('exe'));
    // dialog.showMessageBox(win, {
    //     message: (serve ? 'serve\n' : '') + __dirname + '\n' + exePath + '\n' + process.cwd()
    // })

    return win
}

try {
    app.allowRendererProcessReuse = true
    app.on('ready', () => setTimeout(createWindow, 400))
    app.on('window-all-closed', () => {
        log.info('window-all-closed')
        // app.exit()
        if (process.platform !== 'darwin') {
            app.quit()
        }
    })
    app.on('activate', () => {
        if (win === null) {
            createWindow()
        }
    })
} catch (e) {
}
